// 
//  Copyright 2011  reda
// 
//    Licensed under the Apache License, Version 2.0 (the "License");
//    you may not use this file except in compliance with the License.
//    You may obtain a copy of the License at
// 
//        http://www.apache.org/licenses/LICENSE-2.0
// 
//    Unless required by applicable law or agreed to in writing, software
//    distributed under the License is distributed on an "AS IS" BASIS,
//    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//    See the License for the specific language governing permissions and
//    limitations under the License.
using System;
using ManiacMusicManager.Data.Core;
using NHibernate;
using ManiacMusicManager.Data.DAO.Ifaces;
using System.Collections.Generic;
using ManiacMusicManager.Data.Utils;
using ManiacMusicManager.Data.Exceptions;

namespace ManiacMusicManager.Data.DAO
{
	public class CompilationDAO : AbstractDAO<Compilation>, ICompilationDAO
	{
		public CompilationDAO (ISession session)
			: base(session)
		{
		}
	

		#region ICompilationDAO implementation
		public Compilation GetByPath (string path)
		{
			var parties = path.ToLower().Split('/');
			var last = parties[parties.Length - 1];
			var filterLast = this.SelectByName(last, StringSearchOptions.ExactIgnoreCase);
			
			try {
				this.sessionHolder.BeginSafeBlock();
				foreach(var comp in filterLast) {
					var parent = comp.Parent;
					var i = parties.Length - 2;
					while((parent!=null) && (i >= 0)) {
						if(parent.Name.ToLower() != parties[i])
							break;
						else {
							parent = comp.Parent;
							i--;
						}
					}
					
					if((parent == null) && (i < 0))
						return comp;
				}
				
				return null;
			}
			catch(Exception e) {
				throw new DatabaseException(e);
			}
			finally {
				this.sessionHolder.EndSafeBlock();
			}
		}
		#endregion
	}
}

